package cn.wgx.modules.sys.util;

import cn.hutool.core.bean.BeanUtil;
import cn.wgx.commons.config.CustomConfig;
import cn.wgx.commons.util.CacheUtils;
import cn.wgx.modules.sys.entity.SysConfig;
import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.Map;

@Log4j2
public class SysConfigUtil {


    public final static String SYS_CONFIG = "SYS_CONFIG";

    private final static String ALL_CONFIG = "ALL_CONFIG";


    public static Map<String, String> getAllConfig(){
        Map<String, String> valuesByType = DictUtil.getValuesByType(SYS_CONFIG);
        return valuesByType;
    }

    /**
     * 根据类型获取相关配置
     * cn.wgx.modules.sys.entity.SysConfig.subclass
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getConfigByClass(Class<T> clazz){
        Object o = CacheUtils.get(ALL_CONFIG);
        if(o != null){
            T rtmpConfig = BeanUtil.mapToBean((Map<String, String>)o, clazz, true);
            return rtmpConfig;
        }
        Map<String, String> valuesByType = getAllConfig();
        if(valuesByType == null){
            return null;
        }
        T rtmpConfig = BeanUtil.mapToBean(valuesByType, clazz, true);
        CacheUtils.put(ALL_CONFIG, valuesByType);
        return rtmpConfig;
    }


    public static int updateConfig(Object config){
        if(config == null){
            return (0);
        }
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(config);
        int r = DictUtil.updateByTypeAndKey(SYS_CONFIG, stringObjectMap);
        if(r > 0){
            CacheUtils.remove(ALL_CONFIG);
        }
        return r;
    }




}
